#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "CyS_TP2.h"
#include "aes_dec.h"


void
setup_decryption(EVP_CIPHER_CTX *ctx, char *key, char *iv)
{
    EVP_DecryptInit(ctx, EVP_aes_128_cbc(), (unsigned char *)key, (unsigned char *)iv);
}

char *
decrypt(EVP_CIPHER_CTX *ctx, char *ct, int inl, char *pt)
{
    int ol;

    EVP_DecryptUpdate(ctx, (unsigned char *)pt, &ol, (unsigned char *)ct, inl);
    if (!ol)
    {
        /* no hay bloque para descifrar */
        return NULL;
    }
    pt[ol] = 0;

    return pt;
}

int
tryDecryptAes(char *cryptedText, int len, char *key)
{
    EVP_CIPHER_CTX ctx;
    char iv[16];
    char final[EVP_MAX_BLOCK_LENGTH];
    char plain[512]={0};
    int finalLen;

    memset(iv, 0, 16);

    if (key == NULL)
    {
        fprintf(stderr, "Fatal error: key cannot be null\n");
        exit(EXIT_FAILURE);
    }

    if (cryptedText == NULL)
    {
        fprintf(stderr, "Fatal error: crypted text cannot be null\n");
        exit(EXIT_FAILURE);
    }

    /* inicializar */
    EVP_CIPHER_CTX_init(&ctx);

    EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
            (unsigned char *)key, (unsigned char *)iv);
    //setup_decryption(&ctx, key, iv);
    decrypt(&ctx, cryptedText, len, plain);

    if (plain != NULL)
    {
        if (!isPossible(plain)){
        	EVP_CIPHER_CTX_cleanup(&ctx);
            return 0;
        }
    }

    if (!EVP_DecryptFinal_ex(&ctx, (unsigned char *)final, &finalLen))
    {
        EVP_CIPHER_CTX_cleanup(&ctx);
        return 0;
    }

    final[finalLen] = 0;

    printf("%s", plain);
    printf("%s\n", final);

    EVP_CIPHER_CTX_cleanup(&ctx);

    return 1;
}
